/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package verification;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JPasswordField;

/**
 *
 * @author NATHAN
 */
public class PasswordFieldVerifier extends AbstractValidator {

  int minLength, maxLength;
  boolean canBeNull;

  public PasswordFieldVerifier(JPanel parent, JComponent c, String message, int minLength, int maxLength) {
    super(parent, c, message);
    this.minLength = minLength;
    this.maxLength = maxLength;
    this.canBeNull = false;
  }

  public PasswordFieldVerifier(JPanel parent, JComponent c, String message, int minLength, int maxLength, boolean canBeNull) {
    this(parent, c, message, minLength, maxLength);
    this.canBeNull = canBeNull;
  }

  @Override
  protected boolean validationCriteria(JComponent c) {
    String text = String.copyValueOf(((JPasswordField) c).getPassword());
    text = text.trim();

    if (canBeNull) {
      if (!((text.length() <= maxLength && text.length() >= minLength) || text.length() == 0)) {
        setMessage("Must be at least " + minLength + " and no more than " + maxLength + " characters long.");
        return false;
      }
    } else {
      // empty check
      if ("".equals(text)) {
        return false;
      }  // length check
      if (!((text.length() <= maxLength && text.length() >= minLength))) {
        setMessage("Must be at least " + minLength + " and no more than " + maxLength + " characters long.");
        return false;
      }
    }
    // illegal character check
    for (int i = 0; i < text.length(); i++) {
      if (checkChar(text.charAt(i))) {
        setMessage("Special characters ',./<>?;':\"[]\\{}|`~ are not allowed.");
        return false;
      }
    }
    return true;
  }

  private boolean checkChar(char ch) {
    switch (ch) {
      case ',':
      case '.':
      case '/':
      case '<':
      case '>':
      case '?':
      case ';':
      case '\'':
      case ':':
      case '"':
      case '[':
      case ']':
      case '\\':
      case '{':
      case '}':
      case '|':
      case '`':
      case '~':
        return true;
    }
    return false;
  }
}
